package com.uniknow.app.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.uniknow.app.AppConfig;
import com.uniknow.app.R;
import com.uniknow.app.util.FileUtils;
import com.uniknow.app.util.ImageUtils;
import com.uniknow.app.util.UIHelper;
import com.uniknow.app.widget.NewDataToast;
import com.uniknow.app.widget.ZoomImageView;

public class ImageActivity extends BaseActivity {
	private Handler HandlerUI=null;
	private ZoomImageView zoomImageView;
	private ImageView imageViewThumb;
	private String imgUrl,imgName;
	private Bitmap urlImageBitmap,urlImageBitmapThumb;
	private ProgressBar loadingBar;
	private Button saveBtn;
	
	private static final int DOWNLOAD_PREPARE = 0;
	private static final int DOWNLOAD_WORK = 1;
	private static final int DOWNLOAD_OK = 2;
	private static final int DOWNLOAD_ERROR =3;
	private ProgressBar loadingPro;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image);
		loadingBar = (ProgressBar)findViewById(R.id.ImageActivity_progressBar);
		zoomImageView = (ZoomImageView)findViewById(R.id.ImageActivity_zoomImageView);
		imageViewThumb = (ImageView) findViewById(R.id.ImageActivity_ImageViewThumb);
		saveBtn = (Button)findViewById(R.id.ImageActivity_save);
		loadingPro = (ProgressBar)findViewById(R.id.ImageActivity_progressSlip);
		HandlerUI = new Handler();
        Intent intent = getIntent();
        imgUrl = intent.getStringExtra("imgstr");
        imgName = FileUtils.getFileName(imgUrl);
        urlImageBitmapThumb = ImageUtils.getBitmapByPath(AppConfig.FOLDER_IMG_CACHE+File.separator+imgName);
        imageViewThumb.setImageBitmap(urlImageBitmapThumb);
        zoomImageView.setVisibility(View.GONE);
        saveBtn.setEnabled(false);
        
        if(FileUtils.checkFileExists(AppConfig.FOLDER_IMG+File.separator+imgName)){
            final Runnable runnableUi=new Runnable(){
            	@Override
            	public void run() {
	            	zoomImageView.setImageBitmap(urlImageBitmap);
	            	loadingBar.setVisibility(View.GONE);
	    			loadingPro.setVisibility(View.GONE);
	    			imageViewThumb.setVisibility(View.GONE);
	    			zoomImageView.setVisibility(View.VISIBLE);
	    			saveBtn.setEnabled(true);
	            	}
            	};
            new Thread(){
            	public void run(){
            	loadingBar.setVisibility(View.VISIBLE);
            	urlImageBitmap = ImageUtils.getBitmapByPath(AppConfig.FOLDER_IMG+File.separator+imgName);
            	HandlerUI.post(runnableUi);
            	}
            }.start(); 
        	
        }else{
        	new Thread(){
            	@Override
                public void run() {
                    downloadFile();
                    super.run();
                }
            }.start();
        }
		
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					ImageUtils.saveImageToSD(AppConfig.FOLDER_IMG+File.separator+imgName, urlImageBitmap, 100);
					String msg = getResources().getString(R.string.save_image_success);
					msg=String.format(msg,AppConfig.FOLDER_IMG+File.separator+imgName);
					NewDataToast.makeText(ImageActivity.this, msg, true).show();
					saveBtn.setText(getResources().getString(R.string.save_imaged));
					saveBtn.setEnabled(false);
				} catch (IOException e) {
					e.printStackTrace();
					UIHelper.ToastMessage(ImageActivity.this, R.string.data_parser_failed, 4);
				}
			}
		});
        
	}
	
	/**
     * 文件下载
     */
    private void downloadFile()
    {
        try {
            URL u = new URL(imgUrl.replace("thumb", ""));
            System.out.println("imgsrc = "+imgUrl.replace("thumb", ""));
            URLConnection conn = u.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            fileSize = conn.getContentLength();
            if(fileSize<1||is==null)
            {
                sendMessage(DOWNLOAD_ERROR);
            }else{
                sendMessage(DOWNLOAD_PREPARE);
                FileOutputStream fos = new FileOutputStream((FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+imgName));
                byte[] bytes = new byte[1024];
                int len = -1;
                while((len = is.read(bytes))!=-1)
                {
                    fos.write(bytes, 0, len);
                    downloadSize+=len;
                    sendMessage(DOWNLOAD_WORK);
                }
                sendMessage(DOWNLOAD_OK);
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            sendMessage(DOWNLOAD_ERROR);
            e.printStackTrace();
        }
    }
    /**
     * 文件一共的大小
     */
    int fileSize = 0;
    /**
     * 已经下载的大小
     */
    int downloadSize = 0;
    /**
     * handler处理消息
     */
    private Handler handler = new Handler(){
 
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DOWNLOAD_PREPARE:
            	UIHelper.ToastMessage(ImageActivity.this, R.string.download_ready);
                loadingPro.setVisibility(ProgressBar.VISIBLE);
                loadingPro.setMax(fileSize);
                try {
					FileUtils.creatSDFile(AppConfig.FOLDER_IMG+File.separator+imgName);
				} catch (IOException e1) {
					UIHelper.ToastMessage(ImageActivity.this, R.string.create_file_fail);
					e1.printStackTrace();
				}
                break;
            case DOWNLOAD_WORK:
                loadingPro.setProgress(downloadSize);
                int res = downloadSize*100/fileSize;
                break;
            case DOWNLOAD_OK:
                try {
                    if((FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+imgName).endsWith(".jpg")||(FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+imgName).endsWith(".png")){
                    	FileInputStream fis = new FileInputStream((FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+imgName));
                        zoomImageView.setImageBitmap(BitmapFactory.decodeStream(fis));
                        fis.close();
                        System.out.println("filepath = "+FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+imgName);
                    }
                    downloadSize = 0;
                    fileSize = 0;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
				loadingBar.setVisibility(View.GONE);
				loadingPro.setVisibility(View.GONE);
				imageViewThumb.setVisibility(View.GONE);
				zoomImageView.setVisibility(View.VISIBLE);
				saveBtn.setEnabled(true);
				UIHelper.ToastMessage(ImageActivity.this, R.string.download_success);
                break;
            case DOWNLOAD_ERROR:
            	UIHelper.ToastMessage(ImageActivity.this, R.string.download_fail);
                break;
            }
            super.handleMessage(msg);
        }
    };
    
    /**
     * 给hand发送消息
     * @param what
     */
    private void sendMessage(int what)
    {
       Message m = new Message();
       m.what = what;
       handler.sendMessage(m);
    }

}
